package com.zjh.photoshopstudy.app.user;

import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.provider.MediaStore;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.bitmap.CircleCrop;
import com.bumptech.glide.request.RequestOptions;
import com.zjh.photoshopstudy.Model.AppUserEntity;
import com.zjh.photoshopstudy.R;
import com.zjh.photoshopstudy.Utils.Data;
import com.zjh.photoshopstudy.Utils.SharePreferencesUtils;

import org.greenrobot.eventbus.EventBus;

import java.io.File;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

public class EditUserActivity extends AppCompatActivity {
    ImageView uIcon;
    TextView uAccountNameView;
    TextView uBirthdayView;
    EditText uNameView;
    RadioButton btn1, btn2;
    AppUserEntity userEntity;
    String uIconUri;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_edit_user);
        uIcon = findViewById(R.id.uicon2);
        uAccountNameView = findViewById(R.id.uAccountName);
        uBirthdayView = findViewById(R.id.uBirthday);
        uNameView = findViewById(R.id.uName);
        btn1 = findViewById(R.id.radioButton2);
        btn2 = findViewById(R.id.radioButton);
        userEntity = SharePreferencesUtils.getLoginUser(this);
        Glide.with(this).load(Data.webRoot_URL + userEntity.getuIcon()).apply(RequestOptions.bitmapTransform(new CircleCrop())).into(uIcon);
        uAccountNameView.setText(userEntity.getuAccountName());
        DateFormat bf = new SimpleDateFormat("yyyy-MM-dd");
        uBirthdayView.setText(bf.format(userEntity.getuBirthday()));
        uNameView.setText(userEntity.getuName());
        if (userEntity.getuSex() == 1) {
            btn1.setChecked(true);
        } else {
            btn2.setChecked(true);
        }
        uNameView.setSelection(userEntity.getuName().length());
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == 1 && resultCode == Activity.RESULT_OK) {
            Uri uri = data.getData();
            uIconUri = uri.toString();
            try (Cursor cursor = getContentResolver().query(uri, null, null, null, null)) {
                cursor.moveToNext();
                String path = cursor.getString(cursor.getColumnIndex(MediaStore.Video.Media.DATA));
                UserHttp.uploadIcon(this, new File(path));
            }

        }
    }

    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.uicon2:
                selectIcon();
                break;
            case R.id.radioButton2:
                userEntity.setuSex(1);
                break;
            case R.id.radioButton:
                userEntity.setuSex(0);
                break;
            case R.id.uBirthday:
                showBirthdayDialog();
                break;
            case R.id.button2:
                doUpdate();
                break;

        }
    }

    public void showBirthdayDialog() {
        final Dialog bottomDialog = new Dialog(this, R.style.CenterDialog);
        View contentView = LayoutInflater.from(this).inflate(R.layout.dialog_birthday, null);
        bottomDialog.setContentView(contentView);
        Button save, close;
        final DatePicker dpPicker = contentView.findViewById(R.id.dpPicker);
        save = contentView.findViewById(R.id.save);
        close = contentView.findViewById(R.id.close);
        Date data = userEntity.getuBirthday();
        final Calendar mCalendar = Calendar.getInstance();
        dpPicker.setMaxDate(new Date().getTime());
        if (data != null) {
            mCalendar.setTime(data);
        }
        dpPicker.init(mCalendar.get(Calendar.YEAR), mCalendar.get(Calendar.MONTH), mCalendar.get(Calendar.DAY_OF_MONTH), listener);
        save.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                int y = dpPicker.getYear();
                int m = dpPicker.getMonth() + 1;
                int d = dpPicker.getDayOfMonth();
                String date = y + "-" + m + "-" + d;
                mCalendar.set(y, m - 1, d);
                uBirthdayView.setText(date);
                userEntity.setuBirthday(mCalendar.getTime());
                bottomDialog.dismiss();
            }
        });

        close.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                bottomDialog.dismiss();
            }
        });
        bottomDialog.getWindow().setGravity(Gravity.CENTER);
        bottomDialog.show();
    }

    DatePicker.OnDateChangedListener listener = new DatePicker.OnDateChangedListener() {
        @Override
        public void onDateChanged(DatePicker view, int year, int monthOfYear, int dayOfMonth) {

            if (isDateAfter(view)) {
                Calendar mCalendar = Calendar.getInstance();
                view.init(mCalendar.get(Calendar.YEAR),
                        mCalendar.get(Calendar.MONTH),
                        mCalendar.get(Calendar.DAY_OF_MONTH), this);
            }
        }

        private boolean isDateAfter(DatePicker tempView) {
            Calendar mCalendar = Calendar.getInstance();
            Calendar tempCalendar = Calendar.getInstance();
            tempCalendar.set(tempView.getYear(), tempView.getMonth(),
                    tempView.getDayOfMonth(), 0, 0, 0);
            if (tempCalendar.after(mCalendar))
                return true;
            else
                return false;
        }
    };

    private void doUpdate() {
        String name = uNameView.getText().toString().trim();
        if (name.length() < 5) {
            Toast.makeText(this, "昵称不能小于5位", Toast.LENGTH_SHORT).show();
        } else {
            userEntity.setuName(name);
            UserHttp.updateUser(this, userEntity);
        }
    }

    private void selectIcon() {
        Intent intent = new Intent(Intent.ACTION_PICK);
        intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
        Intent chooser = Intent.createChooser(intent, "选择图片");
        startActivityForResult(chooser, 1);
    }

    public void uploadIconSuccess(String url) {
        Toast.makeText(this, "上传头像成功", Toast.LENGTH_SHORT).show();
        userEntity.setuIcon(url);
        Glide.with(this).load(Data.webRoot_URL + userEntity.getuIcon()).apply(RequestOptions.bitmapTransform(new CircleCrop())).into(uIcon);
    }

    public void updateSuccess(AppUserEntity userEntity) {
        Toast.makeText(this, "更新成功", Toast.LENGTH_SHORT).show();
        SharePreferencesUtils.saveLoginUser(userEntity, this);
        EventBus.getDefault().post(new UserFragment.UpdateUser());
        finish();
    }

    public void updateFail() {
        Toast.makeText(this, "更新失败", Toast.LENGTH_SHORT).show();
    }
}
